package org.softee.extractor.sax;

import java.io.IOException;
import java.io.StringReader;

import javax.xml.parsers.ParserConfigurationException;

import org.softee.extractor.QNameMatcher;
import org.softee.extractor.QNameMatcherFactory;
import org.softee.extractor.sax.helper.ResultHandler;
import org.softee.extractor.sax.helper.XmlExtractor;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;

public class XmlExtractorDomSample {

    public static void main(String[] args) throws Exception {
        String xml = "<ns:root xmlns:ns='urn:namespace'><ns:child>child with namespace</ns:child><child>Child with no namespace</child></ns:root>";

        extract(xml, "child");
        extract(xml, "{}child");
        extract(xml, "{urn:namespace}child");

    }

    public static void extract(final String xml, final String elementName) throws ParserConfigurationException, SAXException, IOException {
        InputSource src = new InputSource(new StringReader(xml));

        // Create a matcher that matches elements by name and optional namespace
        QNameMatcher qNameMatcher = QNameMatcherFactory.combinedNameMatcher(elementName);

        // Create a handler that will receive notifications of matched XML fragments as separate XML Documents
        ResultHandler<Document> documentHandler = new ResultHandler<Document>() {
            @Override
            public void accept(Document document) {
                Element element = document.getDocumentElement();
                System.out.printf("'%s' matched element %s in namespace %s%n",
                        elementName, element.getLocalName(), element.getNamespaceURI());
            }
        };
        XmlExtractor<Document> extractor = XmlExtractorFactory.createDomExtractor(qNameMatcher, documentHandler);
        extractor.process(src);
    }
}
